package persistence;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


import model.Area;



public class AreaDaoImpl implements AreaDao {
	Connection c;

	public AreaDaoImpl() {
		GenericDao gDao = new GenericDao();
		c = gDao.getConnection();
	}

	@Override
	public void salvaArea(Area area) throws SQLException {
		String sql = "INSERT INTO areas VALUES (?,?)";
		PreparedStatement ps = c.prepareStatement(sql);

		ps.setInt(1, area.getIdArea());
		ps.setString(2, area.getNomeArea());

		ps.execute();
		ps.close();

	}

	@Override
	public void editaArea(Area area) throws SQLException {
		String sql = "UPDATE areas SET nomeArea = ? WHERE idArea = ?";
		PreparedStatement ps = c.prepareStatement(sql);
		ps.setString(1, area.getNomeArea());
		ps.setInt(2, area.getIdArea());
		ps.execute();
		ps.close();

	}

	@Override
	public void excluiArea(Area area) throws SQLException {
		String sql = "DELETE areas WHERE idArea = ?";
		PreparedStatement ps = c.prepareStatement(sql);
		ps.setInt(1, area.getIdArea());
		ps.execute();
		ps.close();

	}

	@Override
	public Area pesquisaArea(Area area) throws SQLException {
		Area a = new Area();
		String sql = "SELECT idArea, nomeArea FROM areas WHERE idArea = ?";
		PreparedStatement ps = c.prepareStatement(sql);
		ps.setInt(1, area.getIdArea());
		ResultSet rs = ps.executeQuery();
		if (rs.next()) {
			a.setIdArea(rs.getInt("idArea"));
			a.setNomeArea(rs.getString("nomeArea"));

		}
		ps.close();
		rs.close();
		return a;
	}

}
